﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using STX.Admin.Models.BizArea;
using STX.Domain;
using STX.Service;

namespace STX.Admin.Controllers
{
    public class BizAreaController : BasePages1Controller<BizArea,IndexModel,AddModel,EditModel,QueryModel>
    {
        public BizAreaService BizAreaService { get; set; }

        protected override void OnInit(out Func<BaseService<BizArea>> thisService,
            out Func<IndexModel> getIndexModelFunc, out Func<AddModel> getAddModelFunc,
            out Func<int, EditModel> getEditModelFunc)
        {
            thisService = () => BizAreaService;
            getIndexModelFunc = () => new IndexModel();
            getAddModelFunc = () => new AddModel();
            getEditModelFunc = id =>
            {
                var model = BizAreaService.FindModelById(id);
                if (model == null)
                {
                    throw new Exception("此地方已被删除");
                }
                return new EditModel
                {
                    Id = id,
                    Name = model.Name
                };
            };
        }

        protected override long AddHandler(AddModel addModel)
        {
            return BizAreaService.Add(new BizArea()
            {
                Name = addModel.Name
            });
        }

        protected override bool EditHandler(EditModel editModel)
        {
            var model = BizAreaService.FindModelById(editModel.Id);
            if (model == null)
            {
                throw new Exception("此地方已被删除");
            }
            model.Name = editModel.Name;
            return BizAreaService.Update(model);
        }

        public override JsonResult Delete(int[] ids)
        {
            if (AdminContext.CurrentUser.Position != PositionEnum.SystemPower)
                throw new Exception("你没有权限删除地方");
            return base.Delete(ids);
        }

        protected override IQueryable<BizArea> QueryHandler(QueryModel queryModel, IQueryable<BizArea> queryable)
        {
            return queryable;
        }
    }
}
